<?php
namespace App\Http\Controllers\Business\Admin\Shop;

use App\Models\AdminUser;
use App\Models\Province;
use App\Models\Shop;
use App\Models\Order;
use App\Models\ShopCheck;
use App\Models\ShopEvent;
use App\Models\ShopHistoryEvent;
use App\Models\ShopReview;
use App\Models\ShopUser;
use App\Models\ShopContract;
use App\Models\SmsMessage;
use App\Models\Oss;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redis;
use Log;
use Exception;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Business\Admin\Log\ShopLog;
use App\Models\City;
class ShopManagement{
    //商家列表
    public static function shopManagement($cityid,$starttime = '',$lasttime = '',$firstclassid = '%',$secondclassid = '%',$isdouble = '%',$search = '%',$perpage = 20) {
        if(Auth::guard('adminweb')->user()->isalldata == '1') {
            $userid = '%';
        } else {
            $userid = Auth::guard('adminweb')->id();
        }
        if (!$starttime || !$lasttime) {
            $starttime = '2016-01-01 00:00:00';
            $lasttime = date('Y-m-d H:i:s', time());
        }
        if (($search == '%') || ($search == '')) {
            $data = Shop::where('shops.created_at', '>', $starttime)->where('shops.created_at', '<', $lasttime)->where('shops.maintainerid', 'like', $userid)
                ->join('admin_users', 'admin_users.id', '=', 'shops.maintainerid')
                ->where('shops.status', '1')
                ->where('shops.cityid', $cityid)
                ->whereIn('shops.districtid', $GLOBALS['Districtid'])
                ->where('firstclassid', 'like', $firstclassid)->where('secondclassid', 'like', $secondclassid)
                ->select('shops.id as shopid', 'shops.code as shopcode', 'shops.name as shopname', 'shops.address', 'shops.parentmobile', 'shops.lastevent', 'shops.todayevent', 'shops.firstclassname', 'shops.secondclassname', 'shops.districtname', 'shops.businessareaname', 'shops.qrcode',  'admin_users.mobile', 'admin_users.realname', 'shops.created_at')
                ->orderBy('shops.updated_at', 'desc')
                ->paginate($perpage);
        } else {
            $search = '%' . $search . '%';
            $GLOBALS['search'] = $search;
            $data = Shop::where('shops.created_at', '>', $starttime)->where('shops.created_at', '<', $lasttime)->where('shops.maintainerid', 'like', $userid)
                ->join('admin_users', 'admin_users.id', '=', 'shops.maintainerid')
                ->where('shops.status', '1')
                ->where('shops.cityid', $cityid)
                ->whereIn('shops.districtid', $GLOBALS['Districtid'])
                ->where('firstclassid', 'like', $firstclassid)->where('secondclassid', 'like', $secondclassid)
                ->where(function ($query) {
                    $query->orWhere('shops.name', 'like', $GLOBALS['search'])
                        ->orWhere('shops.code', 'like', $GLOBALS['search'])
                        ->orWhere('admin_users.mobile', 'like', $GLOBALS['search'])
                        ->orWhere('admin_users.realname', 'like', $GLOBALS['search']);
                })
                ->select('shops.id as shopid', 'shops.code as shopcode', 'shops.name as shopname', 'shops.address', 'shops.parentmobile', 'shops.lastevent', 'shops.todayevent', 'shops.firstclassname', 'shops.secondclassname', 'shops.districtname', 'shops.businessareaname', 'shops.qrcode',  'admin_users.mobile', 'admin_users.realname', 'shops.created_at')
                ->orderBy('shops.updated_at', 'desc')
                ->paginate($perpage);
        }
        return ['status' => 'success','data'=>$data];
    }
    //修改商家帐号
    public static function shopAdminUserEdit($shopId,$oldMobile,$newMobile) {
        if(!$shopId || !$oldMobile || !$newMobile) {
            return ['status' => 'failed', 'message' => '请求数据不完整！'];
        }
        $shop = Shop::where('id',$shopId)->where('parentmobile',$oldMobile)->first();
        if(!$shop) {
            return ['status' => 'failed', 'message' => '原手机号码错误！'];
        }
        $oldUser = ShopUser::where('mobile',$oldMobile)->first();
        if(!$oldUser) {
            return ['status' => 'failed', 'message' => '系统错误，无法找到原账号！'];
        }
        $oldShopIds = explode(',', $oldUser['shopid']);
        $oldUserAuth = json_decode($oldUser['auth'],true);
        if(!isset($oldUserAuth[$shopId])||!$oldUserAuth[$shopId]) {
            return ['status' => 'failed', 'message' => '系统错误，原账号权限错误！'];
        }

        Shop::where('id',$shopId)->where('parentmobile',$oldMobile)->update(['parentmobile'=>$newMobile]);
        $newUserShopAuth = $oldUserAuth[$shopId];
        unset($oldUserAuth[$shopId]);
        if(is_array($oldShopIds)) {
            unset($oldShopIds[array_search($shopId, $oldShopIds)]);
        }
        $oldShopIdString = implode(',', $oldShopIds);
        ShopUser::where('mobile',$oldMobile)->update(['auth'=>json_encode($oldUserAuth), 'shopid'=>$oldShopIdString]);
        Redis::del('ShopAuth:'.$oldUser['id']);
        $token=Redis::get('ShopApiToken:UserId:'.$oldUser['id']);
        Redis::del('ShopApiToken:'.$token);
        Redis::del('ShopApiToken:UserId:'.$oldUser['id']);
        $newUser = ShopUser::where('mobile',$newMobile)->first();
        if($newUser) {
            $newUserAuth = $newUser['auth'];
            $newUserAuth = json_decode($newUserAuth,true);
            $newUserAuth[$shopId] = $newUserShopAuth;
            $newUserShopIds = explode(',', $newUser['shopid']);
            if(!empty($newUserShopIds)&&(!in_array($shopId, $newUserShopIds))) {
                array_push($newUserShopIds, $shopId);
            }
            $newUserShopIdString = implode(',', $newUserShopIds);
            ShopUser::where('mobile',$newMobile)->update(['auth'=>json_encode($newUserAuth), 'shopid'=>$newUserShopIdString]);
            Redis::del('ShopAuth:'.$newUser['id']);
            $token=Redis::get('ShopApiToken:UserId:'.$newUser['id']);
            Redis::del('ShopApiToken:'.$token);
            Redis::del('ShopApiToken:UserId:'.$newUser['id']);
        } else {
            $newUserAuth = [$shopId => $newUserShopAuth];
            $newShopUser = ShopUser::create([
                'mobile' => $newMobile,
                'name' => $newMobile,
                'shopid' => $shopId,
                'auth' => json_encode($newUserAuth)
            ]);
            $newShopUser->save();
        }
        $reason = '商家登录账号由"'.$oldMobile.'"修改成"'.$newMobile.'"';
        $shopLog = ShopLog::writeShopLog($shopId,'update_shop_mobile',0,$reason,'');
        return ['status' => 'success', 'message' => '账号信息修改成功！'];
    }
    //新增商家
    public static function addShop($data) {
        if (!$data) {
            return ['status' => 'failed', 'message' => '请求数据不完整！'];
        }
        $shopCode = $data['code'];
        $shopId = Shop::where('code', $shopCode)->pluck('id')->first();
        if($shopId) {
            $shop = Shop::where('code', $shopCode)->update($data);
        } else {
            $shop = Shop::create($data);
            $shop->save();
            $shopId = $shop->id;
        }
        $data = ['shopid' => $shopId];
        return ['status' => 'success', 'message'=>'创建成功', 'data'=>$data];
    }
    //新增商家review
    public static function addShopReview($data) {
        if(!$data) {
            return ['status'=>'failed', 'message'=>'参数失败！'];
        }
        $shopReview = ShopReview::create($data);
        $shopReview->save();
        return ['status'=>'success', 'message'=>'创建成功！'];
    }
    //获取商家详情
    public static function shopDetails($shopid,$cityid) {
        if (!$shopid || !$cityid) {
            return ['status' => 'failed', 'message' => '请求数据不完整！'];
        }
        $data = Shop::where('id',$shopid)->where('cityid',$cityid)->first();
        if(!$data) {
            return ['status' => 'failed', 'message' => '获取信息失败'];
        }
        $data['provincename'] = Province::where('id', $data['provinceid'])->pluck('name')->first();
        return ['status' => 'success','data'=>$data];
    }
    //编辑商家
    public static function editShop($shopId,$shop) {
        if (!$shop || !$shopId) {
            return ['status' => 'failed', 'message' => '请求数据不完整！'];
        }
        Shop::where('id',$shopId)->update($shop);
        return ['status' => 'success', 'message'=>'修改成功'];
    }
    // 修改商家翻贝日
    public static function todayDoubleEdit($shopid,$type, $deductiontype='0',$deductionNote = '') {
        if (!$shopid) {
            return ['status' => 'failed', 'message' => '请求数据不完整！'];
        }
        if($type == '1') {
            //开通翻倍日
            Shop::where('id', $shopid)->update(['todayevent' => $type, 'adminid' => Auth::guard('adminweb')->id()]);
            if(ShopEvent::where('shopid', $shopid)->where('event', date('Y-m-d'))->get()->count()<1) {
                ShopEvent::create([
                    'shopid' => $shopid,
                    'event' => date('Y-m-d'),
                ]);
            }
            if(ShopHistoryEvent::where('shopid', $shopid)->where('event', date('Y-m-d'))->get()->count()<1) {
                ShopHistoryEvent::create([
                    'shopid' => $shopid,
                    'event' => date('Y-m-d')
                ]);
            }
            $doubledayType = "open_doubleday";
            $reason = "开通今天翻倍日";
            if(!empty($deductionNote)){
                $remark = $deductionNote;
            }else{
                $remark = "";
            }
            $shopCheck  = ShopLog::writeShopLog($shopid,$doubledayType,0,$reason,$remark);
            return ['status' => 'success', 'message'=>'修改成功'];
        } else {
            //取消翻倍日
            $result = ShopContract::deductionModel($shopid, $deductiontype);
            if($result) {
                $doubledayType = "cancel_doubleday";
                $reason = "取消今天翻倍日";
                if(!empty($deductionNote)){
                    $remark = $deductionNote;
                }else{
                    $remark = "";
                }
                $shopCheck  = ShopLog::writeShopLog($shopid,$doubledayType,0,$reason,$remark);
                return ['status' => 'success', 'message'=>'修改成功'];
            } else {
                return ['status' => 'failed', 'message'=>'修改失败'];
            }
        }
    }
    //修改商家状态， 上线或者下架
    public static function shopStatusEdit($shopId,$type, $decutionType=0) {
        if (!$shopId) {
            return ['status' => 'failed', 'message' => '请求数据不完整！'];
        }
        //修改上下架状态
        Shop::where('id', $shopId)->update(['status'=>$type,'checktime'=>date('Y-m-d H:i:s',time()),'adminid'=>Auth::guard('adminweb')->id()]);
        if($type == '0') {
            //下架 不影响翻贝日
            //ShopContract::deductionModel($shopId, $decutionType);//扣工资
            //ShopEvent::where('shopid', $shopId)->where('event', date('Y-m-d'))->delete();
            //ShopHistoryEvent::where('shopid', $shopId)->where('event', date('Y-m-d'))->delete();
        } else {
            //上架
            if(ShopEvent::where('shopid', $shopId)->where('event', date('Y-m-d'))->get()->count()<1) {
//                ShopEvent::create([
//                    'shopid' => $shopId,
//                    'event' => date('Y-m-d'),
//                ]);
            }
            if(ShopHistoryEvent::where('shopid', $shopId)->where('event', date('Y-m-d'))->get()->count()<1) {
//                ShopHistoryEvent::create([
//                    'shopid' => $shopId,
//                    'event' => date('Y-m-d')
//                ]);
            }
        }
        return ['status' => 'success', 'message' => '修改成功' ];
    }
    //续签, 获取签约
    public static function renewShop($shopId, $contractorId,$startTime, $lastTime) {
        if(!$shopId || !$startTime || !$lastTime) {
           return ['status'=>'failed', 'message'=>'参数错误'];
        }
        $result = ShopContract::addShopContractModel($shopId, $contractorId, $startTime, $lastTime);
        if($result){
            $maintenanceName = AdminUser::where('id',$contractorId)->pluck('realname')->first();
            if(!$maintenanceName){
                return ['status'=>'failed','message'=>'该维护人不存在'];
            }
            $updateShopMaintenance = Shop::where('id', $shopId)->update(['maintainerid'=>$contractorId,'oldid'=>$contractorId,'oldmaintainer'=>$maintenanceName]);
        }
        if($result == false) {
            return ['status'=>'failed', 'message'=>'续约失败'];
        } else {
            return ['status' => 'success', 'message' => '续约成功'];
        }
    }
    //获取签约时间
    public static function getShopContract($shopId) {
        if(!$shopId) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        $data = ShopContract::where('shopid',$shopId)->orderBy('id', 'desc')->first();
        return ['status'=>'success', 'data'=>$data];
    }
    //修改商家维护人
    public static function updateShopMaintainerId($shopId, $maintainerId) {
        if(!$shopId|| !$maintainerId) {
            return ['status'=>'failed', 'message'=>'参数不对'];
        }
        $shopInfo = Shop::where('shops.id',$shopId)
            ->leftjoin('admin_users','admin_users.id','=','shops.maintainerid')
            ->pluck('admin_users.realname')->first();
        $updateShop = Shop::where('id', $shopId)->update(['maintainerid'=>$maintainerId]);
        $adminUserName = AdminUser::where('id', $maintainerId)->pluck('realname')->first();
        $reason = '维护人由"'.$shopInfo.'"修改成"'.$adminUserName.'"';
        $shopLog = ShopLog::writeShopLog($shopId,'update_shop_maintainer',0,$reason,'');
        return ['status'=>'success', 'message'=>'修改成功'];
    }
    //修改商家维护人
    public static function updateShopOldMaintainer($shopId, $oldMaintainer) {
        if(!$shopId|| !$oldMaintainer) {
            return ['status'=>'failed', 'message'=>'参数不对'];
        }
        $shopInfo = Shop::where('id',$shopId)->select('id','oldid','oldmaintainer')->first();
        $updateShop = Shop::where('id', $shopId)->update(['oldmaintainer'=>$oldMaintainer]);
        $reason = '';
        if(empty($shopInfo['oldmaintainer'])){
            $reason .= '原系统维护人由"无系统维护人"修改成"'.$oldMaintainer.'"';
        }elseif(strcmp($shopInfo['oldmaintainer'],$oldMaintainer) != '0'){
            $reason .= '原系统维护人由"'.$shopInfo['oldmaintainer'].'"修改成"'.$oldMaintainer.'"';
        }
        $oldmaintainer = ShopLog::writeShopLog($shopId,'update_shop_oldmaintainer',0,$reason,'');
        return ['status'=>'success', 'message'=>'修改成功'];
    }
    //修改商家帐号, type为shop, shop_review
    public static function updateShopParentMobile($shopId, $oldParentMobile, $newParentMobile, $type='shop') {
        if(!$shopId || !$oldParentMobile || !$newParentMobile ||!$type) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        if($type == 'shop') {
            $result = Shop::where('id', $shopId)->where('parentmobile', $oldParentMobile)->update(['parentmobile'=>$newParentMobile]);
            if($result) {
                $oldShopUser = ShopUser::where('mobile', $oldParentMobile)->first();
                if($oldShopUser) {
                    $oldAuth = $oldShopUser->auth;
                    $oldAuthArray = json_decode($oldAuth, true);
                    if(is_array($oldAuthArray)) {
                        unset($oldAuthArray[$shopId]);
                        $oldShopUser->auth = json_encode($oldAuthArray);
                        $oldShopUser->save();
                        Redis::del('ShopAuth:'.$oldShopUser->id);
                        $token=Redis::get('ShopApiToken:UserId:'.$oldShopUser->id);
                        Redis::del('ShopApiToken:'.$token);
                        Redis::del('ShopApiToken:UserId:'.$oldShopUser->id);
                    }
                }
                $shopUser = ShopUser::where('mobile', $newParentMobile)->first();
                if($shopUser) {
                    $auth = $shopUser->auth;
                    $authArray = json_decode($auth, true);
                    if(is_array($authArray)) {
                        $authArray[$shopId] = ['Admin', "Account", "OrderManager", "CollectMoney", "DoubleCalendar"];
                    } else {
                        $authArray = [
                            $shopId => ['Admin', "Account", "OrderManager", "CollectMoney", "DoubleCalendar"]
                        ];
                    }
                    $shopUser->auth = json_encode($authArray);
                    $shopUser->save();
                    Redis::del('ShopAuth:'.$shopUser->id);
                    $token=Redis::get('ShopApiToken:UserId:'.$shopUser->id);
                    Redis::del('ShopApiToken:'.$token);
                    Redis::del('ShopApiToken:UserId:'.$shopUser->id);
                } else {
                    $authArray = [
                        $shopId => ['Admin', "Account", "OrderManager", "CollectMoney", "DoubleCalendar"]
                    ];
                    $shopUser = ShopUser::create([
                        'name' => $newParentMobile, //TODO
                        'mobile' => $newParentMobile,
                        'auth' =>  json_encode($authArray),
                    ]);
                    $shopUser->save();
                }
                return ['status'=>'success', 'message'=>'修改成功'];
            }
            return ['status'=>'failed', 'message'=>'更新失败'];
        } else {
            //shop_review
            $shopReview = ShopReview::where('id', $shopId)->where('parentmobile', $oldParentMobile)->first();
            if($shopReview) {
                $parentName = $shopReview->parentname;
                $shopReview->parentmobile = $newParentMobile;
                $shopReview->save();
                $count = ShopUser::where('mobile', $newParentMobile)->get()->count();
                if($count < 1) {
                    $shopUser = ShopUser::create([
                        'name' => $parentName,
                        'mobile' => $newParentMobile
                    ]);
                    $shopUser->save();
                }
                return ['status'=>'success', 'message'=>'修改成功'];
            }
            return ['status'=>'failed', 'message'=>'更新失败'];
        }
    }
    //商务待处理列表
    public static function staffVerifyManagement($cityid,$starttime = '',$lasttime = '',$search = '%') {
        if(Auth::guard('adminweb')->user()->isalldata == '1') {
            $userid = '%';
        } else {
            $userid = Auth::guard('adminweb')->id();
        }
        if (!$starttime || !$lasttime) {
            $starttime = '2016-01-01 00:00:00';
            $lasttime = date('Y-m-d H:i:s', time());
        }
        if ($search != '%') {
            $search = '%' . $search . '%';
        }
        $GLOBALS['search'] = $search;
        $data = ShopReview::where('shop_reviews.cityid',$cityid)
            ->where('shop_reviews.status', '0')
            ->where('shop_reviews.created_at','>',$starttime)->where('shop_reviews.created_at','<',$lasttime)
            ->whereIn('shop_reviews.districtid',$GLOBALS['Districtid'])
            ->join('admin_users','admin_users.id','=','shop_reviews.maintainerid')
            ->where('maintainerid','like',$userid)
            ->where(function($query){
                $query->orWhere('shop_reviews.code','like',$GLOBALS['search'])
                    ->orWhere('shop_reviews.name','like',$GLOBALS['search']);
            })
            ->select('shop_reviews.id as shopreviewid','shop_reviews.created_at','shop_reviews.code as shopcode','shop_reviews.name as shopname','shop_reviews.parentmobile','shop_reviews.updatecontent','admin_users.mobile as managermobile','admin_users.realname as managername','shop_reviews.note')
            ->orderBy('shop_reviews.updated_at', 'desc')
            ->get();

        return ['status' => 'success','data'=>$data];
    }
    //编辑商家shop_review表
    public static function editShopReview($shopreviewid,$shop) {
        if (!$shop || !$shopreviewid) {
            return ['status' => 'failed', 'message' => '请求数据不完整！'];
        }
        ShopReview::where('id',$shopreviewid)->update($shop);
        return ['status' => 'success', 'message'=>'更新成功！'];
    }
    //删除商家review表
    public static function delShopReview($shopreviewid){
        if (!$shopreviewid) {
            return ['status' => 'failed', 'message' => '请求数据不完整！'];
        }
        ShopReview::where('id',$shopreviewid)->where('firstverifyid',Auth::guard('adminweb')->id())->where('shopuserid','0')->delete();
        return ['status' => 'success', 'message'=>'删除成功'];
    }
    //客服删除shop_review
    public static function delShopReviewByCustomer($shopreviewid){
        if (!$shopreviewid) {
            return ['status' => 'failed', 'message' => '请求数据不完整！'];
        }
        ShopReview::where('id',$shopreviewid)->where('status', '1')->delete();
        return ['status' => 'success', 'message'=>'删除成功'];
    }
    //客服待处理列表
    public static function verifyManagement($cityid,$starttime = '',$lasttime = '',$search = '') {
        if (!$starttime || !$lasttime) {
            $starttime = '2016-01-01 00:00:00';
            $lasttime = date('Y-m-d H:i:s', time());
        }
        if ($search != '') {
            $search = '%' . $search . '%';
            $GLOBALS['search'] = $search;
            $data = ShopReview::where('shop_reviews.cityid', $cityid)->where('shop_reviews.created_at', '>', $starttime)->where('shop_reviews.created_at', '<', $lasttime)
                ->join('admin_users', 'admin_users.id', '=', 'shop_reviews.maintainerid')
                ->where('shop_reviews.status', '1')
                ->whereIn('shop_reviews.districtid', $GLOBALS['Districtid'])
                ->where(function ($query) {
                    $query->orWhere('shop_reviews.code', 'like', $GLOBALS['search'])
                        ->orWhere('shop_reviews.name', 'like', $GLOBALS['search']);
                })
                ->select('shop_reviews.id as shopreviewid', 'shop_reviews.created_at', 'shop_reviews.code as shopcode', 'shop_reviews.parentmobile', 'shop_reviews.name as shopname', 'shop_reviews.updatecontent', 'admin_users.mobile as managermobile', 'admin_users.realname as managername', 'shop_reviews.note')
                ->orderBy('shop_reviews.updated_at', 'desc')
                ->get();
        } else {
            $data = ShopReview::where('shop_reviews.cityid', $cityid)->where('shop_reviews.created_at', '>', $starttime)->where('shop_reviews.created_at', '<', $lasttime)
                ->join('admin_users', 'admin_users.id', '=', 'shop_reviews.maintainerid')
                ->where('shop_reviews.status', '1')
                ->whereIn('shop_reviews.districtid', $GLOBALS['Districtid'])
                ->select('shop_reviews.id as shopreviewid', 'shop_reviews.created_at', 'shop_reviews.code as shopcode', 'shop_reviews.parentmobile', 'shop_reviews.name as shopname', 'shop_reviews.updatecontent', 'admin_users.mobile as managermobile', 'admin_users.realname as managername', 'shop_reviews.note')
                ->orderBy('shop_reviews.updated_at', 'desc')
                ->get();
        }
        return ['status' => 'success','data'=>$data];
    }
    //通过shop_reviews表id来获取shop_review信息
    public static function shopReviewDetails($shopreviewid,$cityid) {
        if (!$shopreviewid || !$cityid) {
            return ['status' => 'failed', 'message' => '请求数据不完整！'];
        }
        $data = ShopReview::where('id',$shopreviewid)->where('cityid',$cityid)->whereIn('districtid',$GLOBALS['Districtid'])->first();
        if(!$data) {
            return ['status'=>'failed', 'message'=>'获取信息失败'];
        }
        $data['provincename'] = Province::where('id', $data['provinceid'])->pluck('name')->first();
        return ['status' => 'success','data'=>$data];
    }
    //通过shopid来获取shop_review信息
    public static function getShopReviewByShopId($shopid, $cityid) {
        if (!$shopid || !$cityid) {
            return ['status' => 'failed', 'message' => '请求数据不完整！'];
        }
        $data = ShopReview::where('shopid',$shopid)->where('cityid',$cityid)
            ->whereIn('districtid',$GLOBALS['Districtid'])
            ->orderBy('created_at', 'desc')->first();
        return ['status' => 'success','data'=>$data];
    }
    //商家下架列表
    public static function banShopManagement($cityid,$starttime = '',$lasttime = '',$search = '%') {
        if(!$cityid) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        if (!$starttime || !$lasttime) {
            $starttime = '2016-01-01 00:00:00';
            $lasttime = date('Y-m-d H:i:s', time());
        }
        if ($search != '%') {
            $search = '%' . $search . '%';
        }
        $GLOBALS['search'] = $search;
        $data = Shop::where('shops.status','0')
            ->where('shops.cityid', $cityid)
            ->where('shops.updated_at','>',$starttime)->where('shops.updated_at','<',$lasttime)
            ->join('admin_users','admin_users.id','=','shops.maintainerid')
            ->where(function($query){
                $query->orWhere('shops.code','like',$GLOBALS['search'])
                    ->orWhere('shops.name','like',$GLOBALS['search'])
                    ->orWhere('admin_users.mobile','like',$GLOBALS['search'])
                    ->orWhere('admin_users.realname','like',$GLOBALS['search']);
            })
            ->select('shops.id as shopid','shops.cityname','shops.parentmobile','shops.firstclassname','shops.secondclassname','shops.todayevent','shops.created_at','shops.code as shopcode','shops.name as shopname','shops.address','admin_users.mobile as managermobile','admin_users.realname as managername','shops.checktime')
            ->orderBy('shops.updated_at', 'desc')
            ->get();
        return ['status' => 'success','data'=>$data];
    }
    //商家状态列表
    public static function shopStatusList($cityId, $startTime='', $lastTime='', $search='',$skip=0, $take=50) {
        if(!$cityId) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        if(!$startTime||!$lastTime) {
            $startTime = '2016-07-01 00:00:00';
            $lastTime = date('Y-m-d H:i:s');
        }
        $cityName = City::lists('name','id');
        if($search) {
            $GLOBALS['search'] = $search;
            $shopInfo = DB::select('select a.*,b.* from (select shopid,created_at as check_created from 91fbw_shop_check order by check_created desc) as a join (select id,name,code,status,cityid,grade from 91fbw_shops) as b on b.id = a.shopid where b.cityid = "'.$cityId.'" and a.check_created >= "'.$startTime.'" and a.check_created <= "'.$lastTime.'" and (b.name like "%'.$GLOBALS['search'].'%" or b.code = "'.$GLOBALS['search'].'") group by a.shopid order by a.check_created desc limit '.$skip.','.$take);
        } else {
            $shopInfo  = DB::select('select a.*,b.* from (select shopid,created_at as check_created from 91fbw_shop_check order by check_created desc) as a join (select id,name,code,status,cityid,grade from 91fbw_shops) as b on b.id = a.shopid where b.cityid = "'.$cityId.'" and a.check_created >= "'.$startTime.'" and a.check_created <= "'.$lastTime.'" group by a.shopid order by a.check_created desc limit '.$skip.','.$take);
        }
        $data = [];
        if(!empty($shopInfo)){
            foreach($shopInfo as $k=>$v) {
                $data[$k]['shopid'] = $v->shopid;
                $data[$k]['code'] = $v->code;
                $data[$k]['shopname']= $v->name;
                $data[$k]['cityname'] = $cityName[$v->cityid];
                $data[$k]['status'] = $v->status;
                $data[$k]['created_at'] = $v->check_created;
                $data[$k]['grade'] = $v->grade;
            }
        }
        return ['status'=>'success', 'data'=>$data];
    }
    //商家状态总计
    public static function getShopStatusTotal($cityId, $startTime='', $lastTime='', $search='') {
        if(!$cityId) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        if(!$startTime||!$lastTime) {
            $startTime = '2016-07-01 00:00:00';
            $lastTime = date('Y-m-d H:i:s');
        }
        if($search) {
            $GLOBALS['search'] = $search;
            $shopInfo =  DB::select('select a.*,b.* from (select shopid,created_at as check_created from 91fbw_shop_check order by check_created desc) as a join (select id,name,code,status,cityid from 91fbw_shops) as b on b.id = a.shopid where b.cityid = "'.$cityId.'" and a.check_created >= "'.$startTime.'" and a.check_created <= "'.$lastTime.'" and (b.name like "%'.$GLOBALS['search'].'%" or b.code = "'.$GLOBALS['search'].'") group by a.shopid');
        } else {
            $shopInfo =  DB::select('select a.*,b.* from (select shopid,created_at as check_created from 91fbw_shop_check order by check_created desc) as a join (select id,name,code,status,cityid from 91fbw_shops) as b on b.id = a.shopid where b.cityid = "'.$cityId.'" and a.check_created >= "'.$startTime.'" and a.check_created <= "'.$lastTime.'"  group by a.shopid ');
        }
        $data = count($shopInfo);
        return ['status'=>'success', 'data'=>$data];
    }
    //通过shopid获取商家状态列表
    public static function getShopStatusDetailByShopId($shopId) {
        if(!$shopId) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        $shop = Shop::where('id', $shopId)->select('name', 'code')->first();
        if(!$shop) {
            return ['status'=>'failed', 'message'=>'获取信息错误'];
        }
        $lists = ShopCheck::where('shopid', $shopId)->orderBy('created_at', 'desc')->get();
        foreach($lists as $key=>$value) {
            if (!in_array($value['type'], array('shop_set_doublecalendar'))) {
                $lists[$key]['operator'] = AdminUser::where('id', $value['adminid'])->pluck('realname')->first();
            } else {
                $shopUser = ShopUser::where('id', $value['adminid'])->pluck('name')->first();
                $lists[$key]['operator'] = $shopUser;
            }
            $lists[$key]['realname'] = AdminUser::where('id', $value['maintainerid'])->pluck('realname')->first();
        }
        $data = [
            'lists' => $lists,
            'shopname' => $shop['name'],
            'shopcode' => $shop['code'],
        ];
        return ['status'=>'success', 'data'=>$data];
    }
    //商家最后活动日列表续签
    public static function shopLastEventList($cityId, $startTime='', $lastTime='', $perpage=50) {
        if (!$startTime || !$lastTime) {
            $startTime = '2016-07-01 00:00:00';
            $lastTime = date('Y-m-d H:i:s', time());
        }
//        $shops = Shop::where('shops.cityid', $cityId)->where('shops.updated_at', '>=', $startTime)->where('shops.updated_at', '<=', $lastTime)
//            ->join('admin_users', 'shops.maintainerid', '=', 'admin_users.id')
//            ->orderBy('shops.updated_at', 'desc')
//            ->select('shops.id as shopid', 'shops.code as shopcode', 'shops.name as shopname', 'shops.status','admin_users.realname as adminname', 'admin_users.mobile as adminmobile')
//            ->paginate($perpage);
//        foreach($shops as $k=>$value) {
//            $shopId = $shops[$k]['shopid'];
//            $shops[$k]['lastevent'] = ShopEvent::where('shopid', $shopId)->orderBy('event', 'desc')->pluck('event')->first();
//        }
        $shops = DB::select("select a.*,b.* from (select shopid,contractorid,lasttime ,91fbw_shop_contract.created_at ,realname,mobile from 91fbw_shop_contract join 91fbw_admin_users on 91fbw_shop_contract.contractorid =91fbw_admin_users.id  order by created_at desc) as a join(select id as shopid,code as shopcode,name as shopname ,status as shopstatus,maintainerid,cityid from 91fbw_shops) as b on b.shopid = a.shopid  where b.cityid='".$cityId."' group by a.shopid order by b.shopstatus desc ,a.lasttime asc");
        return ['status'=>'success', 'data'=>$shops];
    }
    //导出商家最后活动日列表
    public static function exportShopLastEventList($cityId, $startTime='', $lastTime='') {
        if (!$startTime || !$lastTime) {
            $startTime = '2016-07-01 00:00:00';
            $lastTime = date('Y-m-d H:i:s', time());
        }
//        $shops = Shop::where('cityid', $cityId)
//            ->where('updated_at', '>=', $startTime)
//            ->where('updated_at', '<=', $lastTime)
//            ->orderBy('updated_at', 'desc')
//            ->select('id as shopid', 'code as shopcode', 'name as shopname', 'status', 'address')
//            ->get();
//        foreach($shops as $k=>$value) {
//            $shopId = $shops[$k]['shopid'];
//            $shops[$k]['lastevent'] = ShopEvent::where('shopid', $shopId)->orderBy('event', 'desc')->pluck('event')->first();
//        }
        $shops = DB::select("select a.*,b.* from (select shopid,contractorid,lasttime ,91fbw_shop_contract.created_at ,realname,mobile from 91fbw_shop_contract join 91fbw_admin_users on 91fbw_shop_contract.contractorid =91fbw_admin_users.id  order by created_at desc) as a join(select id as shopid,code as shopcode,name as shopname ,status as shopstatus,maintainerid,cityid from 91fbw_shops) as b on b.shopid = a.shopid  where b.cityid='".$cityId."' group by a.shopid order by b.shopstatus desc ,a.lasttime asc");
        return ['status'=>'success', 'data'=>$shops];
    }
    //翻倍日列表
    public static function doubleDayManagement($cityid,$starttime = '',$lasttime = ''){
        $data = [];
        if (!$starttime || !$lasttime) {
            for($i = 0;$i < 10;$i++) {
                $data = array_merge($data,array(
                    date("Y-m-d",time()-$i*24*3600) =>
                        ShopHistoryEvent::where('shop_historyevents.event',date("Y-m-d",time()-$i*24*3600))
                            ->join('shops','shops.id','=','shop_historyevents.shopid')
                            ->where('shops.cityid',$cityid)
                            ->where('shops.status','1')
                            ->whereIn('shops.districtid',$GLOBALS['Districtid'])
                            ->get()
                            ->count()
                ));
            }
        } else {
            $starttime = strtotime($starttime);
            $lasttime = strtotime($lasttime);
            if($lasttime<$starttime) {
                return ['status' => 'failed', 'message' => '起始时间错误！'];
            }
            $interval = $days=round(($lasttime-$starttime)/3600/24);
            for($i = 0;$i <= $interval;$i ++) {
                 $data = array_merge($data,array(
                    date("Y-m-d",$lasttime-$i*24*3600) =>
                        ShopHistoryEvent::where('shop_historyevents.event',date("Y-m-d",$lasttime-$i*24*3600))
                            ->join('shops','shops.id','=','shop_historyevents.shopid')
                            ->where('shops.cityid',$cityid)
                            ->where('shops.status','1')
                            ->whereIn('shops.districtid',$GLOBALS['Districtid'])
                            ->get()
                            ->count()
                ));
            }
        }
        return ['status' => 'success','data'=>$data];
    }
    //夜场管理列表
    public static function nightEventManagement($cityid, $starttime='', $lasttime='') {
        if(!$cityid) {
            return ['status'=>'failed', 'message'=>'参数不对'];
        }
        if(!$starttime || !$lasttime) {
            $starttime = '2016-01-01 00:00:00';
            $lasttime = date('Y-m-d H:i:s');
        }
        $data = Shop::where('nightevent', '1')->where('cityid', $cityid)
            ->select('id as shopid', 'code', 'name', 'firstclassname', 'secondclassname', 'contactnumber','nightevent','forbidnightevent', 'status', 'updated_at')
            ->orderBy('updated_at', 'desc')
            ->get();
        return ['status'=>'success', 'data'=>$data];
    }
    //禁止或恢复商家夜场状态
    public static function updateShopForbidNightEvent($shopid, $cityid, $type) {
        if(!$cityid || !$shopid) {
            return ['status'=>'failed', 'message'=>'参数不对'];
        }
        Shop::where('cityid', $cityid)->where('id', $shopid)->update(['forbidnightevent'=>$type]);
        return ['status'=>'success', 'message'=>'修改成功'];
    }
    //获取商家信息活动日
    public static function getShopEvent($shopid) {
        if(!$shopid) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        $data = ShopEvent::where('shopid', $shopid)->select('event')->get();
        return ['status'=>'success', 'data'=>$data];
    }
    //获取商家合约开始时间，结束时间
    public static function getLastContract($shopId) {
        if(!$shopId) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        $data = ShopContract::where('shopid', $shopId)->orderBy('id', 'desc')->select('starttime', 'lasttime')->first();
        return ['status'=>'success', 'data'=>$data];
    }
    //翻倍日详情
    public static function doubleDayDetails($doubletime,$firstclassid = '%',$secondclassid = '%',$status = '%',$search = '%',$cityId) {
        if (!$doubletime || !$cityId) {
            return ['status' => 'failed', 'message' => '请求数据不完整！'];
        }
        if ($search != '%') {
            $search = '%' . $search . '%';
        }
        $GLOBALS['search'] = $search;
        $data = ShopHistoryEvent::where('shop_historyevents.event',$doubletime)
            ->join('shops','shops.id','=','shop_historyevents.shopid')
            ->leftjoin('admin_users','admin_users.id','=','shops.maintainerid')
            ->where('shops.firstclassid','like',$firstclassid)
            ->where('shops.secondclassid','like',$secondclassid)
            ->whereIn('shops.districtid',$GLOBALS['Districtid'])
            ->where('shops.todayevent','like',$status)
            ->where('shops.status','1')
            ->where('shops.cityid',$cityId)
            ->where(function($query){
                $query->orWhere('shops.code','like',$GLOBALS['search'])
                    ->orWhere('shops.name','like',$GLOBALS['search']);
            })->orderBy('shop_historyevents.created_at','desc')->select('shops.id as shopid','shops.firstclassname','shops.secondclassname','shops.name as shopname','shops.code as shopcode','shops.todayevent','shops.contactnumber','shops.grade','admin_users.realname','shops.oldmaintainer')->get();
        return ['status' => 'success','data'=>$data];
    }
    //导出翻贝日
    public static function exportDoubleDay($doubletime,$cityId) {
        if(!$doubletime || !$cityId) {
            return ['status' => 'failed', 'message' => '请求数据不完整！'];
        }
        $data = ShopHistoryEvent::where('shop_historyevents.event',$doubletime)
            ->join('shops','shops.id','=','shop_historyevents.shopid')
            ->leftjoin('admin_users','shops.maintainerid', '=', 'admin_users.id')
            ->where('shops.status', '1')
            ->where('shops.cityid',$cityId)
            ->select('shops.id as shopid','shops.firstclassid','shops.secondclassid','shops.firstclassname','shops.secondclassname','shops.name as shopname','shops.code as shopcode','shops.todayevent','shops.contactnumber','shops.oldmaintainer','admin_users.realname as realname','shops.grade','shop_historyevents.event as shopevent')
            ->orderBy('shop_historyevents.created_at','desc')
            ->get();
        return ['status'=>'success', 'data'=>$data];
    }
    //通过商家id 获取合同签约个数
    public static function getShopContractCountByShopId($shopId) {
        $count = ShopContract::where('shopid', $shopId)->get()->count();
        return $count;
    }
    //通过商家id,一级分类，二级分类，获取有效的订单
    public static function getValidOrderCountByShopId($shopId,$firstClassId, $secondClassId, $startTime='', $lastTime='') {
        if(!$shopId || !$firstClassId || !$secondClassId) {
            return 0;
        }
        if(!$startTime || !$lastTime) {
            $startTime = '2016-07-01';
            $lastTime = date("Y-m-d") . " 23:59:59";
        }
        $count = 0;
        if($firstClassId == 1) {
            if($secondClassId == 7 || $secondClassId == 8) {
                //甜点饮品/其他美食——消费满30元的计为有效单
                $count = Order::where('shopid', $shopId)->where('orderamount', '>=',30)->where('created_at','>=', $startTime)->where('created_at', '<=', $lastTime)->count();
            } elseif($secondClassId==1||$secondClassId==2||$secondClassId==3||$secondClassId==4||$secondClassId==5||$secondClassId==6) {
                //火锅/自助餐/海鲜/中餐/西餐/[咖啡/酒吧/茶室]——消费满50元的计为有效单；
                $count = Order::where('shopid', $shopId)->where('orderamount', '>=',50)->where('created_at','>=', $startTime)->where('created_at', '<=', $lastTime)->count();
            }
        } elseif($firstClassId == 2) {
            if($secondClassId==10||$secondClassId==11||$secondClassId==12||$secondClassId==13||$secondClassId==15||$secondClassId==16) {
                //洗浴汗蒸/养生保健/密室逃脱/桌游电玩/农家乐/私人影院——消费满30元的计为有效单；
                $count = Order::where('shopid', $shopId)->where('orderamount', '>=', 30)->where('created_at', '>=', $startTime)->where('created_at', '<=', $lastTime)->count();
            } elseif($secondClassId==9||$secondClassId==14) {
                //KTV/运动健身/酒吧——消费满50元的计为有效单；
                $count = Order::where('shopid', $shopId)->where('orderamount', '>=', 50)->where('created_at', '>=', $startTime)->where('created_at', '<=', $lastTime)->count();
            }
        } elseif($firstClassId == 3) {
            if($secondClassId==19||$secondClassId==20||$secondClassId==22||$secondClassId==23||$secondClassId==24||$secondClassId==25||$secondClassId==26) {
                //美容美甲/洗衣店/母婴亲子/宠物医院/汽车美容——消费满30元的计为有效单；
                $count = Order::where('shopid', $shopId)->where('orderamount', '>=', 30)->where('created_at', '>=', $startTime)->where('created_at', '<=', $lastTime)->count();
            } elseif($secondClassId==17||$secondClassId==18||$secondClassId==20||$secondClassId==21||$secondClassId==27) {
                //服饰购物/教育培训/鲜花/快消品//婚庆摄影写真——消费满50元的计为有效单；
                $count = Order::where('shopid', $shopId)->where('orderamount', '>=', 50)->where('created_at', '>=', $startTime)->where('created_at', '<=', $lastTime)->count();
            }
        } elseif($firstClassId == 4) {
            //酒店：——消费满50元的计为有效单；
            $count = Order::where('shopid', $shopId)->where('orderamount', '>=',50)->where('created_at','>=', $startTime)->where('created_at', '<=', $lastTime)->count();
        } elseif($firstClassId == 5) {
            //旅游——消费满50元的计为有效单；
            $count = Order::where('shopid', $shopId)->where('orderamount', '>=',50)->where('created_at','>=', $startTime)->where('created_at', '<=', $lastTime)->count();
        }
        return $count;
    }
    //新增商家帐号
    public static function addShopUser($name, $mobile, $auth=[], $shopId='') {
        if(!$name || !$mobile ) {
            return ['status'=>'failed', 'message'=>'参数不对！'];
        }
        $oldShopUser = ShopUser::where('mobile', $mobile)->first();
        if($oldShopUser) {
            $shopUserId = $oldShopUser->id;
            $oldAuthJson = $oldShopUser->auth;
            $oldShopIdString = $oldShopUser->shopid;
            $oldAuth = json_decode($oldAuthJson, true);
            if(!empty($auth)) {
                foreach($auth as $key => $value) {
                    $oldAuth[$key] = $value;
                }
                $oldShopUser->auth = json_encode($oldAuth);
                if($shopId) {
                    if($oldShopIdString) {
                        $oldShopUser->shopid = $oldShopIdString . ',' . $shopId;
                    } else {
                        $oldShopUser->shopid = $shopId;
                    }
                }
                $oldShopUser->save();
                //更新权限
                Redis::del('ShopAuth:'.$shopUserId);
            }
        } else {
            $shopUser = ShopUser::create([
                'name' => $name,
                'mobile' => $mobile,
                'auth' => json_encode($auth),
                'shopid' => $shopId
            ]);
            $shopUser->save();
            $shopUserId = $shopUser->id;
        }
        $data = ['shopuserid' => $shopUserId];
        return ['status'=>'success', 'message'=>'添加成功！', 'data'=>$data];
    }
    //新增商家活动日
    public static function addShopEvent($shopId, $event) {
        if(!$shopId || !$event) {
            return ['status' => 'failed', 'message' => '请求数据不完整！'];
        }
        $eventArray = explode(',', $event);
        if(!empty($eventArray)) {
            ShopEvent::where('shopid', $shopId)->delete();
        }
        $today = date('Y-m-d');
        sort($eventArray); //排序
        $isToday = '0';
        $nextEvent = "2018-12-31";
        $isNext = '0';
        foreach($eventArray as $list) {
            if(empty($list)) {
                continue;
            }
            $list = trim($list);
            $list = date('Y-m-d', strtotime($list));
            if($list == $today) {
                $isToday = '1';
            }
            if(($list > $today) && ($nextEvent > $list)) {
                $nextEvent = $list;
                $isNext = '1';
            }
            ShopEvent::create([
                'shopid' => $shopId,
                'event' => $list
            ]);
        }
        if($isToday) {
            Shop::where('id', $shopId)->update(['todayevent'=>'1']);
        }
        if($isNext) {
            Shop::where('id', $shopId)->update(['nextevent'=>$nextEvent]);
        }

        return ['status'=>'success', 'message'=>'添加成功'];
    }
    //新增商家状态日志
    public static function addShopStatus($shopId, $type, $withholdtype=0, $reason='', $remark='') {
        if(!$shopId || !$type) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        $shopContract = ShopContract::where('shopid', $shopId)->orderBy('id', 'desc')->first();
        if($shopContract) {
            $contractorId  = $shopContract->contractorid;
            $contractorName = AdminUser::where('id', $contractorId)->pluck('realname')->first();
            $adminUser = Auth::guard('adminweb')->user();
            $maintainerId = $adminUser->id;
            $maintainerName = $adminUser->realname;
            $shopCheck = ShopCheck::create([
                'shopid' => $shopId,
                'type' => $type,
                'withholdtype' => $withholdtype,
                'reason' => $reason,
                'remark' => $remark,
                'contractorid' => $contractorId,
                'contractorname' => $contractorName,
                'maintainerid' => $maintainerId,
                'maintainername' => $maintainerName,
            ]);
            return ['status'=>'success', 'message'=>'新增成功'];
        } else {
            return ['status'=>'failed', 'message'=>'新增失败'];
        }
    }
    //通过商家id获取商家名称
    public static function getShopNameByShopId($shopId) {
        if(!$shopId) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        $shopName = Shop::where('id', $shopId)->pluck('name')->first();
        return ['status'=>'success', 'data'=>$shopName];
    }
    //第一次入驻或者续约的时候给商家发信息
    public static function sendSmsToShopForFirstEnterOrRenew($mobile, $shopName, $cardholder, $bankCard, $mode=0) {
        if(!$mobile||!$shopName||!$cardholder||!$bankCard) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        $length = strlen($bankCard);
        $bankCard = substr($bankCard, $length-4, 4);
        $result = SmsMessage::firstRunToShop($mobile, $shopName, $cardholder, $bankCard, $mode);
        return ['status'=>'success', 'message'=>'发送成功'];
    }
    //阿里云oss 把临时文件夹下的文件迁移到正式文件夹下
    public static function migrationSingleFile($from, $to) {
        if (!$from || !$to) {
            return false;
        }
        try {
            if (strstr($from, 'temp')) {
                $result = Oss::cutFile($from, $to);
                if ($result == false) {
                    return false;
                } else {
                    return true;
                }
            } else {
                return false;
            }
        } catch(Exception $e) {
            return false;
        }
    }
    //阿里云oss 把商家环境组图由临时文件夹下迁移到正式文件下
    public static function migrationPhotos($shopId, $photos) {
        if(!$shopId || !$photos) {
            return '';
        }
        $photoArray = json_decode($photos, true);
        if(!is_array($photoArray)) {
            return '';
        }
        $i = 1;
        $path = "upload/shop/". $shopId . "/photo" .time();
        $data = [];
        try {
            foreach ($photoArray as $list) {
                $newList = $path . $i;
                if (strstr($list, 'temp')) {
                    $result = Oss::cutFile($list, $newList);
                    if ($result) {
                        array_push($data, $newList);
                    } else {
                        array_push($data, $list);
                    }
                } else {
                    array_push($data, $list);
                }
                $i++;
            }
            return json_encode($data);
        } catch(Exception $e) {
            return '';
        }
    }
    //阿里云oss 把商家商品组图由临时文件夹下迁移到正式文件下
    public static function migrationGoodsPhotos($shopId, $goodsPhotos) {
        if(!$shopId || !$goodsPhotos) {
            return '';
        }
        $goodsPhotoArray = json_decode($goodsPhotos, true);
        if(!is_array($goodsPhotoArray)) {
            return '';
        }
        $i = 1;
        $data = [];
        $newPath = 'upload/shop/' . $shopId .'/goods'.time();
        try {
            foreach ($goodsPhotoArray as $list) {
                $newList = $list;
                $url = $list['url'];
                $newUrl = $newPath . $i;
                if (strstr($url, 'temp')) {
                    $result = Oss::cutFile($url, $newUrl);
                    if ($result) {
                        $newList['url'] = $newUrl;
                    }
                }
                array_push($data, $newList);
                ++$i;
            }
            return json_encode($data);
        } catch(Exception $e) {
            return '';
        }
    }
    //近期无翻倍日的商家列表
    public static function shopWithoutEventList($cityId,$perpage=20, $page=1) {
        if(empty($cityId) ||!is_numeric($cityId)){
            return ['status'=>'failed', 'message'=>'城市定位错误'];
        };
        $skip = ($page-1)*$perpage;
        $take = $perpage;
        $dateTime = date('Y-m-d',time());
        $shopEventInfo = Shop::where('shops.status','1')
            ->where('shops.cityid',$cityId)
            ->where('lastevent','<',$dateTime)
            ->where('nextevent','=','0000-00-00')
            ->leftjoin('admin_users','shops.maintainerid','=','admin_users.id')
            ->select('shops.id as shopid','shops.code as shopcode','shops.name as shopname','shops.status','shops.address as shopaddress','shops.lastevent','shops.districtname','admin_users.realname')
            ->orderBy('shops.id','desc')
            ->skip($skip)
            ->take($take)
            ->get();
        return ['status'=>'success','data'=>$shopEventInfo];
    }
    //导出近期无翻倍日的商家列表
    public static function exportShopWithoutEventList($cityId) {
        if(empty($cityId) || !is_numeric($cityId)){
            return ['status'=>'failed','message'=>'城市定位错误'];
        }
        $dateTime = date('Y-m-d',time());
        $shopEventInfo = Shop::where('shops.status','1')
            ->where('shops.cityid',$cityId)
            ->where('lastevent','<',$dateTime)
            ->where('nextevent','=','0000-00-00')
            ->leftjoin('admin_users','shops.maintainerid','=','admin_users.id')
            ->select('shops.id as shopid','shops.code as shopcode','shops.name as shopname','shops.status','shops.address as shopaddress','shops.lastevent','shops.districtname','admin_users.realname')
            ->orderBy('shops.id','desc')
            ->get();
        return ['status'=>'success','data'=>$shopEventInfo];
    }

    //添加操作商家的日志
    protected static function operateShopLogAdd($shopid,$doubledayType,$reason,$remark){
        //商家日志
        $user = Auth::guard('adminweb')->user();
        $dateTime = date('Y-m-d H:i:s',time());
        //商家日誌
        $doubledayData = array(
            'shopid'=>$shopid,
            'type'=>$doubledayType,
            'reason'=>$reason,
            'remark'=>$remark,
            'contractorid'=>$user['id'],
            'contractorname'=>$user['realname'],
            'maintainerid'=>$user['id'],
            'maintainername'=>$user['realname'],
            'created_at'=>$dateTime,
            'updated_at'=>$dateTime,
            'withholdtype'=>0,
        );
        $cancelDoubleday = ShopCheck::create($doubledayData);
        $cancelDoubleday->save();
        return ['status'=>'success','message'=>'成功'];
    }

    //判断添加商家的是商务人员还是客户人员和后台人员，是就返回登录的商务人员信息，不是就返回所有的商务人员信息
    public static function getBusinessPersonnel($cityId){
        $data = [];
        //获取登录后台人员信息
        $adminUser = Auth::guard('adminweb')->user();
        if($adminUser['roleid'] ==  13){
            $data['roletype'] = 1;
            $data['roleinfo']['adminid'] = $adminUser['id'];
            $data['roleinfo']['realname'] = $adminUser['realname'];
            $data['roleinfo']['mobile'] = $adminUser['mobile'];
        }else{
            $data['roletype'] = 2;
            $data['roleinfo'] = AdminUser::where('status',1)
                ->where(function($query){
                    $query->orWhere('roleid',13)
                        ->orWhere('id',30);
                })->where('cityid',$cityId)
                ->select('id as adminid','realname','mobile')
                ->get();
        }
        return ['status'=>'success','data'=>$data];
    }
    //修改待审核和审核不通过的商家中的维护人
    public static function updateShopReviewMaintenance($shopReviewId, $maintainerId){
        if(!$shopReviewId || !$maintainerId){
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        $updateShop = ShopReview::where('id', $shopReviewId)->update(['maintainerid'=>$maintainerId]);
        return ['status'=>'success', 'message'=>'修改成功'];
    }
    //修改商家级别
    public static function updateShopGrade($shopId,$shopGrade,$cityId){
        if(!$shopId || !$shopGrade || !$cityId){
            return ['status'=>'failed','message'=>'参数错误'];
        }
        $shopInfo = Shop::where('id',$shopId)->select('id','grade')->first();
        if(!$shopInfo){
            return ['status'=>'failed','message'=>'该商家不存在'];
        }
        if(!in_array($shopGrade,array('A级','B级','C级','D级'))){
            return ['status'=>'failed','message'=>'请选择正确的商家级别'];
        }
        $updateShopGrade = Shop::where('id', $shopId)->update(['grade'=>$shopGrade]);
        if($shopInfo['grade'] != $shopGrade){
            $reason = '商家级别由'.$shopInfo['grade'].'修改成'.$shopGrade;
            $shopLog = ShopLog::writeShopLog($shopId,'update_shop_grade',0,$reason,'');
        }
        return ['status'=>'success', 'message'=>'修改成功'];
    }
}